package com.linxz.framework.protocol.Interceptors;

import com.google.gson.Gson;
import com.linxz.evens.AuthError;
import com.linxz.framework.protocol.resp.BaseBean;
import com.linxz.framework.utils.SharedPreferencesUtils;
import org.greenrobot.eventbus.EventBus;
import okhttp3.MediaType;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
/**
 * @author Linxz
 * 创建日期：2019年10月09日 23:10
 * version：v4.5.4
 * 描述：
 */
public class TokenInterceptor extends BaseInterceptor{
    @Override
    public Response intercept(Chain chain) {
        try {
            Request request=chain.request();
            Request newRequest=request.newBuilder()
                    .addHeader("Content-Type","application/json")
                    .addHeader("token", SharedPreferencesUtils.getCustomAppProfile("token"))
                    .build();
            Response response = chain.proceed(newRequest);
            MediaType mediaType = response.body().contentType();
            String content = response.body().string();
            BaseBean baseBean=new Gson().fromJson(content,BaseBean.class);
            if (baseBean.authError()){
                EventBus.getDefault().post(new AuthError());
            }
            return response.newBuilder()
                    .body(ResponseBody.create(mediaType, content))
                    .build();
        } catch (Exception e) {
            e.printStackTrace();
            return new Response.Builder()
                    .code(404)
                    .addHeader("Content-Type", "application/json")
                    .body(ResponseBody.create(MediaType.parse("application/json"), "{}"))
                    .message("网络异常")
                    .request(chain.request())
                    .protocol(Protocol.HTTP_1_1)
                    .build();
        }
    }
}
